/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/11/21
 **/
'use strict';
import "babel-polyfill";

import React from 'react';
import ReactDOM from  'react-dom';
import {msg}  from 'iflux';
import { Select,Radio, Row, Col, Button, Modal, message, Popconfirm, Table, Tabs, Switch} from 'antd';
import 'antd/dist/antd.less'
const Option = Select.Option;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const TabPane = Tabs.TabPane;
import webApi from './web-api';

const columns = [{
  title: '项目名称',
  dataIndex: 'projectName',
}, {
  title: '版本号',
  dataIndex: 'version',
}, {
  title: '环境',
  dataIndex: 'envCode'
}, {
  title: '执行时间',
  dataIndex: 'publishTime',
}, {
  title: '状态',
  dataIndex: 'status'
}, {
  title: '操作人',
  dataIndex: 'username'
}];

const historyColum = [{
  title: '项目名称',
  dataIndex: 'name',
}, {
  title: '版本号',
  dataIndex: 'version',
}, {
  title: 'git分支',
  dataIndex: 'branch'
}, {
  title: '执行时间',
  dataIndex: 'publishTime',
}, {
  title: '邮箱地址',
  dataIndex: 'email',
}, {
  title: '操作人',
  dataIndex: 'username'
}];
var App = React.createClass({

  getInitialState (){
    return  {
      packages:[],
      versions:[],
      iconLoading:false,
      logLoading:false,
      historyLoading:false,
      selectPackage:'',
      selectVersion:'',
      selectEnv:'test',
      publishLogs:[],
      activeKey:'1',
      versionHistories:[],
      syncTemplate:false,
      pagination:{
        total:0,
        pageSize:10,
        current:0
      },
      historyPage:{
        total:0,
        pageSize:10,
        current:0
      }
    };
  },

  componentDidMount() {
    this._loadPackage();
  },

  render() {
    let packages = [
       <Option value ="">请选择一个包</Option>
    ];
    this.state.packages.forEach(packageItem=>{
     packages.push(<Option value={packageItem}>{packageItem}</Option>);

    });

    let versions = [];
    this.state.versions.forEach(versionItem=>{
      versions.push(<Option value={versionItem}>{versionItem}</Option>);
    });

    return <div style={{marginTop:50}}>
      <Row type="flex" justify="space-around" align="middle">
        <Col span={12}>
          <div>
            <RadioGroup defaultValue="test" onChange={this._changeEnv} size="large">
              <RadioButton value="dev">开发环境</RadioButton>
              <RadioButton value="test">测试环境</RadioButton>
              <RadioButton value="gray">灰度环境</RadioButton>
              <RadioButton value="prod">生产环境</RadioButton>
            </RadioGroup>
          </div>
          <br/>

          <div>
            <Select style={{ width: 220 }} onChange={this._changePackage} defaultValue="" size="large">
              {packages}
            </Select>

            <Select style={{ width: 180 ,marginLeft:10}} onChange={this._changeVersion} value={this.state.selectVersion} size="large">
              {versions}
            </Select>
          </div>
          <br/>

          <div>
            <Switch checkedChildren={'是'} unCheckedChildren={'否'} onChange={this._syncTemplate}/>
            <span style={{marginLeft:10}}>同步其它模板</span>
          </div>

          <br/>
          <Popconfirm title="确认要部署到环境吗？" onConfirm={this._deploy} okText="是" cancelText="否">
            <Button type="primary" icon="poweroff" loading={this.state.iconLoading}>
              部署
            </Button>
          </Popconfirm>

          <Button type="ghost" onClick={this._getLogs} style={{marginLeft:10}}>查看日志</Button>
          <Button onClick={this._handOk} style={{marginLeft:10}}>登录</Button>
          <Button onClick={this._rebuildTpl} style={{marginLeft:10}}>reBuildTpl</Button>

        </Col>
      </Row>

      <Row style={{marginTop:40}} type="flex" justify="space-around" align="middle">
        <Col span={12}>
          <Tabs type="card" activeKey={this.state.activeKey} onTabClick={this._onTabClick}>
            <TabPane tab="部署记录" key="1">
              <Table columns={columns} bordered loading={this.state.logLoading}
                     dataSource={this.state.publishLogs}
                     pagination={this.state.pagination}
                     onChange={this._getPublishLogs}/>
            </TabPane>

            <TabPane tab="看看是谁打的版本" key="2">
              <Table columns={historyColum} bordered loading={this.state.historyLoading}
                     dataSource={this.state.versionHistories}
                     pagination={this.state.historyPage}
                     onChange={this._getVersionHistories}/>
            </TabPane>
          </Tabs>
        </Col>
      </Row>
    </div>
  },

  async _syncTemplate (checked){
    this.setState({syncTemplate:checked});
  },

  /**
   * 加载所有可用的包信息
   * @private
   */
  async _loadPackage (){
    let packages = await webApi.getAllpackage();
    this.setState({packages,versions:[]});
  },

  /**
   * 当选中一个包后, 把可用的版本信息都加载过来..
   * @private
   */
  async _changePackage(value){
    let pageageName = value;
    let pagination = this.state.pagination;
    pagination.current = 0;
    pagination.total = 0;

    if(pageageName){
      let result  =  await  webApi.getPackageVersions({pageageName});
      console.log(result);
      let allItems = Object.keys(result.versions).slice(0,30);
      // for(let version in result.versions){
      //   allItems.push(version);
      // }
      this.setState({
        versions:allItems,
        selectPackage:value,
        selectVersion:allItems[0],
        publishLogs:[],
        versionHistories:[],
        activeKey:'1',
        historyPage:pagination,
        pagination});
    }
  },

  /**
   * 部署包到环境中去信息.
   * @private
   */
  async _deploy(){
    this.setState({iconLoading:true});
    let name = this.state.selectPackage;
    let version = this.state.selectVersion;
    let envCode = this.state.selectEnv;
    let syncTemplate = this.state.syncTemplate;
    if (!name) {
      message.warning('请选择项目名称！', 3);
      return;
    }
    if (!version) {
      message.warning('请选择版本号！', 3);
      return;
    }

    let result = await webApi.deployTpl({name,version,envCode,syncTemplate});

    if (result.result && result.result === 'login') {
      message.warning(result.message+'，需要登录获取管理员权限', 3);
    } else {
      message.success(result.message, 3);
    }
    this.setState({iconLoading:false});
  },

  async _getLogs() {
    await this._getPublishLogs();
    await this._getVersionHistories();
  },

  /**
   * 查询部署日志
   * @private
   */
  async _getPublishLogs(e,pagination=this.state.pagination) {
    let envCode = this.state.selectEnv;
    let projectName = this.state.selectPackage;
    if (!projectName) {
      message.warning('请选择项目名称！', 3);
      return;
    }
    this.setState({logLoading:true});
    let pageNum = pagination.current;
    let pageSize = pagination.pageSize;

    let result = await webApi.getPublishLogs({envCode,projectName,pageNum,pageSize});
    let data = result.data;
    let publishLogs = [];
    for (let i = 0; i < data.publishLogs.length; i++) {
      let obj = data.publishLogs[i];
      if (obj.status) {
        obj.status = '操作成功';
      } else {
        obj.status = '操作失败';
      }
      publishLogs.push(obj);
    }
    pagination.total = data.totalCount ? data.totalCount : 0;
    this.setState({publishLogs, pagination, logLoading:false});
  },

  /**
   * 获取版本历史
   * @param pagination
   */
  async _getVersionHistories(e,pagination=this.state.historyPage) {
    let name = this.state.selectPackage;
    if (!name) {
      return;
    }
    this.setState({historyLoading:true});
    let pageNum = pagination.current;
    let pageSize = pagination.pageSize;

    let result = await webApi.getVersionHistories({name,pageNum,pageSize});
    let data = result.data;
    let versionHistories = data.versionHistories ? data.versionHistories : [];
    pagination.total = data.totalCount ? data.totalCount : 0;
    this.setState({versionHistories, historyPage:pagination, historyLoading:false});
  },

  /**
   * 选择版本号
   * @param version
   * @private
   */
  async _changeVersion(version) {
    this.setState({selectVersion:version});
  },

  /**
   * 选择部署环境
   * @param env
   * @private
   */
  async _changeEnv(e) {
    let env = e.target.value;
    let pagination = this.state.pagination;
    pagination.current = 0;
    pagination.total = 0;
    this.setState({selectEnv:env, publishLogs:[], pagination, activeKey: '1'});
  },

  async _onTabClick(key) {
    this.setState({activeKey:key});
  },

    async _rebuildTpl() {
        let envCode = this.state.selectEnv;

        Modal.confirm({
            title: 'Confirm',
            content: '确定要重新打环境['+envCode+']中的模板包',
            okText: '确认',
            cancelText: '取消',
            onOk: async ()=>{
                let result = await webApi.rebuildTpl({envCode});
            }
        });

   },

  async _confirmDeploy() {
    let name = this.state.selectPackage;
    let version = this.state.selectVersion;
    if (!name) {
      message.warning('请选择项目名称！', 3);
      return;
    }
    if (!version) {
      message.warning('请选择版本号！', 3);
      return;
    }
    Modal.confirm({
      title: 'Confirm',
      content: '确定要部署该模块到环境中去吗？',
      okText: '确认',
      cancelText: '取消',
      onOk:this._deploy
    });
  },

  _handOk() {
    location.href = 'login';
  }
});

ReactDOM.render(<App></App>,document.getElementById('tpl-deploy'));
